#include "addticketdialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QDoubleSpinBox>
#include <QSpinBox>
#include <QTimeEdit>
#include <QPushButton>
#include <QMessageBox>
#include <QDateTime>
#include <QGroupBox>

AddTicketDialog::AddTicketDialog(const QString& ticketType, QWidget *parent)
    : QDialog(parent)
    , currentTicketType(ticketType)
{
    setupUI();
    setupConnections();
    generateDefaultTicketId();
    
    setWindowTitle("添加新票种");
    setModal(true);
    resize(400, 500);
}

AddTicketDialog::~AddTicketDialog()
{
}

void AddTicketDialog::setupUI()
{
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    
    // 基本信息组
    QGroupBox *basicGroup = new QGroupBox("基本信息", this);
    QGridLayout *basicLayout = new QGridLayout(basicGroup);
    
    basicLayout->addWidget(new QLabel("票种ID:"), 0, 0);
    ticketIdEdit = new QLineEdit(this);
    ticketIdEdit->setPlaceholderText("请输入票种ID（如：T001）");
    basicLayout->addWidget(ticketIdEdit, 0, 1);
    
    basicLayout->addWidget(new QLabel("票种名称:"), 1, 0);
    ticketNameEdit = new QLineEdit(this);
    ticketNameEdit->setText("新票种");
    basicLayout->addWidget(ticketNameEdit, 1, 1);
    
    basicLayout->addWidget(new QLabel("票种类型:"), 2, 0);
    ticketTypeCombo = new QComboBox(this);
    ticketTypeCombo->addItems({"Train", "Car", "Plane"});
    int index = ticketTypeCombo->findText(currentTicketType);
    if (index >= 0) {
        ticketTypeCombo->setCurrentIndex(index);
    }
    basicLayout->addWidget(ticketTypeCombo, 2, 1);
    
    // 路线信息组
    QGroupBox *routeGroup = new QGroupBox("路线信息", this);
    QGridLayout *routeLayout = new QGridLayout(routeGroup);
    
    routeLayout->addWidget(new QLabel("出发地:"), 0, 0);
    departureLocationEdit = new QLineEdit(this);
    routeLayout->addWidget(departureLocationEdit, 0, 1);
    
    routeLayout->addWidget(new QLabel("到达地:"), 1, 0);
    arrivalLocationEdit = new QLineEdit(this);
    routeLayout->addWidget(arrivalLocationEdit, 1, 1);
    
    routeLayout->addWidget(new QLabel("列车编号:"), 2, 0);
    trainNumberEdit = new QLineEdit(this);
    routeLayout->addWidget(trainNumberEdit, 2, 1);
    
    // 时间信息组
    QGroupBox *timeGroup = new QGroupBox("时间信息", this);
    QGridLayout *timeLayout = new QGridLayout(timeGroup);
    
    timeLayout->addWidget(new QLabel("出发时间:"), 0, 0);
    departureTimeEdit = new QTimeEdit(this);
    departureTimeEdit->setTime(QTime(8, 0));
    timeLayout->addWidget(departureTimeEdit, 0, 1);
    
    timeLayout->addWidget(new QLabel("到达时间:"), 1, 0);
    arrivalTimeEdit = new QTimeEdit(this);
    arrivalTimeEdit->setTime(QTime(12, 0));
    timeLayout->addWidget(arrivalTimeEdit, 1, 1);
    
    // 其他信息组
    QGroupBox *otherGroup = new QGroupBox("其他信息", this);
    QGridLayout *otherLayout = new QGridLayout(otherGroup);
    
    otherLayout->addWidget(new QLabel("价格:"), 0, 0);
    priceSpinBox = new QDoubleSpinBox(this);
    priceSpinBox->setRange(0.0, 99999.99);
    priceSpinBox->setValue(100.0);
    priceSpinBox->setSuffix(" 元");
    otherLayout->addWidget(priceSpinBox, 0, 1);
    
    otherLayout->addWidget(new QLabel("库存:"), 1, 0);
    stockSpinBox = new QSpinBox(this);
    stockSpinBox->setRange(0, 99999);
    stockSpinBox->setValue(100);
    otherLayout->addWidget(stockSpinBox, 1, 1);
    
    otherLayout->addWidget(new QLabel("状态:"), 2, 0);
    statusCombo = new QComboBox(this);
    statusCombo->addItems({"可用", "不可用"});
    statusCombo->setCurrentText("可用");
    otherLayout->addWidget(statusCombo, 2, 1);
    
    // 按钮组
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    okButton = new QPushButton("确定", this);
    cancelButton = new QPushButton("取消", this);
    buttonLayout->addStretch();
    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(cancelButton);
    
    // 添加到主布局
    mainLayout->addWidget(basicGroup);
    mainLayout->addWidget(routeGroup);
    mainLayout->addWidget(timeGroup);
    mainLayout->addWidget(otherGroup);
    mainLayout->addLayout(buttonLayout);
    
    // 根据票种类型设置默认值
    onTicketTypeChanged();
}

void AddTicketDialog::setupConnections()
{
    connect(okButton, &QPushButton::clicked, this, &AddTicketDialog::onOkClicked);
    connect(cancelButton, &QPushButton::clicked, this, &AddTicketDialog::onCancelClicked);
    connect(ticketTypeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &AddTicketDialog::onTicketTypeChanged);
}

void AddTicketDialog::generateDefaultTicketId()
{
    QString type = ticketTypeCombo->currentText();
    QString prefix;
    
    if (type == "Train") {
        prefix = "T";
    } else if (type == "Car") {
        prefix = "C";
    } else if (type == "Plane") {
        prefix = "P";
    } else {
        prefix = "T";
    }
    
    QString timestamp = QString::number(QDateTime::currentSecsSinceEpoch()).right(4);
    QString defaultId = prefix + timestamp;
    ticketIdEdit->setText(defaultId);
}

void AddTicketDialog::onTicketTypeChanged()
{
    QString type = ticketTypeCombo->currentText();
    currentTicketType = type;
    
    // 根据票种类型设置默认的出发地和到达地
    if (type == "Train") {
        departureLocationEdit->setText("北京");
        arrivalLocationEdit->setText("上海");
        trainNumberEdit->setText("G" + QString::number(QDateTime::currentSecsSinceEpoch()).right(3));
    } else if (type == "Car") {
        departureLocationEdit->setText("广州");
        arrivalLocationEdit->setText("深圳");
        trainNumberEdit->setText("BUS" + QString::number(QDateTime::currentSecsSinceEpoch()).right(3));
    } else if (type == "Plane") {
        departureLocationEdit->setText("成都");
        arrivalLocationEdit->setText("重庆");
        trainNumberEdit->setText("CA" + QString::number(QDateTime::currentSecsSinceEpoch()).right(3));
    }
    
    // 重新生成默认票种ID
    generateDefaultTicketId();
}

bool AddTicketDialog::validateInput()
{
    if (ticketIdEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "输入错误", "票种ID不能为空！");
        ticketIdEdit->setFocus();
        return false;
    }
    
    if (ticketNameEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "输入错误", "票种名称不能为空！");
        ticketNameEdit->setFocus();
        return false;
    }
    
    if (departureLocationEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "输入错误", "出发地不能为空！");
        departureLocationEdit->setFocus();
        return false;
    }
    
    if (arrivalLocationEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "输入错误", "到达地不能为空！");
        arrivalLocationEdit->setFocus();
        return false;
    }
    
    if (trainNumberEdit->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "输入错误", "列车编号不能为空！");
        trainNumberEdit->setFocus();
        return false;
    }
    
    return true;
}

void AddTicketDialog::onOkClicked()
{
    if (!validateInput()) {
        return;
    }
    
    accept();
}

void AddTicketDialog::onCancelClicked()
{
    reject();
}

QString AddTicketDialog::getTicketId() const
{
    return ticketIdEdit->text().trimmed();
}

QJsonObject AddTicketDialog::getTicketParams() const
{
    QJsonObject params;
    params["ticket_id"] = getTicketId();
    params["ticket_name"] = ticketNameEdit->text().trimmed();
    params["ticket_type"] = ticketTypeCombo->currentText();
    params["departure_location"] = departureLocationEdit->text().trimmed();
    params["arrival_location"] = arrivalLocationEdit->text().trimmed();
    params["price"] = priceSpinBox->value();
    params["stock"] = stockSpinBox->value();
    params["status"] = statusCombo->currentText();
    params["departure_time"] = departureTimeEdit->time().toString("HH:mm");
    params["arrival_time"] = arrivalTimeEdit->time().toString("HH:mm");
    params["train_number"] = trainNumberEdit->text().trimmed();
    
    return params;
}
